/// <reference path="../../../../../global.d.ts" />

/* global writeBackDIYForm */

/**
 * 函数用于在小类tag点击的时候触发
 * @param {string} val 添加DIY表单的小类tag名称，exp：银行
 */
function AddNewFreeOption (val) {
  layer.msg('加载中', {
    icon: 16,
    shade: 0.01
  })
  /** 获取对应小类id（数据库意义的id） */
  let uID = $(`input#${val}`).attr(`value`)
  /** 获取服务器上的表单数据 */
  let ajaxUrl = String($('#get_new_free_form').val())
  $.ajax(ajaxUrl, {
    method: 'POST',
    data: {m_group: uID},
    success: (data) => {
      // data.id 是数据库的表单id，至少目前看来是废的，已和后端确认
      // if (data.m_id) {
      if (data.formData.length > 0) {
        writeBackDIYForm(data)
      } else {
        addNewHiddenFree(11, uID, val)
      }
    },
    error: function (data) {
      console.clear()
      console.log(data)
    }
  })
}
/** 用于移除指定的DIY表单 */
function RemoveNewFreeOption (val) {
  let uID = $(`input#${val}`).attr(`value`)
  let targetHiddenInput = $(`input[value='${uID}']`).filter(function () {
    if (/^hidden_free/.test($(this).attr('name'))) {
      return this
    }
  })
  if (targetHiddenInput.length > 1) {
    alert('发生严重错误，请联系后台管理员')
    throw new Error(`targetHiddenInput多于一个`)
  } else {
    targetHiddenInput.parent().remove()
    if ($(`[inori-diy-data='${uID}']`).length === 1) {
      $(`[inori-diy-data='${uID}']`).remove()
    } else if (targetHiddenInput.siblings('.button').length === 0) {
      let errorValue = $(`[inori-diy-data='${uID}']`).length.toString()
      throw new Error(errorValue)
    }
  }
}
/** 用于添加指定id的自由表单框框 */
function addNewHiddenFree (formID, uID, val) {
  /** formID 暂时想不出有什么情况需要 */
  let freeID = $('#hiddenFreeCounter').val()
  freeID++

  let templ = `
<div id="hidden_free_${freeID}" class="hdden_free_wrap">
  <div style="width:100%;height:1px;clear:both;"></div>
  <div class = "wrap_title">小类：${val}</div>
  <div class="addNewHiddenFormLine">
    <select
      class="addNewHiddenFormLineType" form='not_submit'
      aria-multiple = 'false'
      aria-placeholder="请选择新增表单类型"
    >
      <option></option>
      <optgroup label="">
        <option value="1">数字输入</option>
      </optgroup>
      <optgroup label="">
        <option value="2">单选</option>
      </optgroup>
      <optgroup label="">
        <option value="3">多选</option>
      </optgroup>
    </select>
    <div class="button">
        <button onclick='addNewHiddenFormLine(this, event)'>添加</button>
    </div>
  </div>
  <input type="hidden" class='hiddenLineCounter' name="lineCounter" value="3" form='not_submit'>
  <input type="hidden" name="hidden_free[1][id]" value="${uID}">
  <input type="hidden" name="hidden_free[1][value]" value="${val}">

  <!-- 最后一个元素必须是div，插入元素定位为最后一个div之前 -->
  <div class="button">
    页面提交前必须先提交本区域！
    <br>
    <button onclick='postThisHiddenLine(this, event)'>保存</button>
  </div>
</div>
<script id = 'addFreeScript'>
  $('#hidden_free_${freeID} .addNewHiddenFormLineType').select2({
    placeholder: '请选择新增表单类型',
    tags: false,
    multiple: false,
    width: 'element'
  })
  setTimeout(()=>{$('#addFreeScript').remove()}, 0)
</script>
  `.trim()
  $('#hdden_free_form_wrap').append(templ)
  $('#hiddenFreeCounter').val(freeID)
}
/** 用于添加指定类型的DIY表单行，也就是一个问题 */
function addNewHiddenFormLine (_this, evt) {
  let nowFormID = $(_this).closest('.addNewHiddenFormLine').parent().attr('id').match(/\d+/)[0]
  /** 一级数值 */
  let freeCounter = nowFormID
  /** 二级数值 */
  let lineCounter = $(_this).closest('.addNewHiddenFormLine').siblings('.hiddenLineCounter').val()
  lineCounter++
  /** 数字输入模板 */
  let numberTempl = `
<div class="input_wrap number_input">
  <div class="title"><input type="text" form='not_submit' name="hidden_free[${freeCounter}][${lineCounter}][title]" id="hidden_free_${freeCounter}_${lineCounter}_title" placeholder="名称"></div>
  <!-- 固定隐藏input，用于后端分辨该行表单类型 -->
  <input type='hidden' name='type' value='1'>
  <div class="alt_data">
    <select
      form = 'not_submit' name="hidden_free[${freeCounter}][${lineCounter}][alt_data]" id="hidden_free_${freeCounter}_${lineCounter}_alt_data"
      aria-multiple = 'false'
      aria-placeholder="请选择取值方向"
    >
      <option></option>
      <optgroup label="">
          <option value="大于">大于</option>
          <option value="大于等于">大于等于</option>
          <option value="小于">小于</option>
          <option value="小于等于">小于等于</option>
          <option value="等于">等于</option>
        </optgroup>
    </select>
  </div>
  <div class="main_data">
    <input type="text" form='not_submit' name="hidden_free[${freeCounter}][${lineCounter}][main_data]" id="hidden_free_${freeCounter}_${lineCounter}_main_data" placeholder="数值" pattern="[\\d\.]+">
  </div>
  <div class="button">
    <button onclick='deleteThisHiddenLine(this)'>删除</button>
  </div>
</div>
<script id='tempmlScript'>
  $('#hidden_free_${freeCounter}_${lineCounter}_alt_data').select2({
    placeholder: '请选择取值方向',
    tags: false,
    multiple: false,
    width: 'element'
  })
  setTimeout(()=>{$('#tempmlScript').remove()}, 0)
</script>
  `.trim()
  /** 单选模板 */
  let singleTempl = `
<div class="input_wrap single_select">
  <div class="title"><input type="text" form='not_submit' name="hidden_free[${freeCounter}][${lineCounter}][title]" id="hidden_free_${freeCounter}_${lineCounter}_title" placeholder="名称"></div>
  <!-- 固定隐藏input，用于后端分辨该行表单类型 -->
  <input type='hidden' name='type' value='2'>
  <div class="alt_data">
    <select
      form = 'not_submit' name="hidden_free[${freeCounter}][${lineCounter}][alt_data]" id="hidden_free_${freeCounter}_${lineCounter}_alt_data"
    >
      <option></option>
      <optgroup label="暂无选项">
        </optgroup>
    </select>
  </div>
  <div class="main_data">
      <select
        form = 'not_submit' name="hidden_free[${freeCounter}][${lineCounter}][main_data]" id="hidden_free_${freeCounter}_${lineCounter}_main_data"
      >
        <option inori-id='here-inori'></option>
      </select>
  </div>
  <div class="button" onclick='deleteThisHiddenLine(this)'>
    <button onclick='deleteThisHiddenLine(this)'>删除</button>
  </div>
</div>
<script id='tempmlScript'>
  $('#hidden_free_${freeCounter}_${lineCounter}_alt_data').select2({
    placeholder: '无需选择',
    tags: false,
    multiple: false,
    width: 'element'
  })
  $('#hidden_free_${freeCounter}_${lineCounter}_main_data').select2({
    placeholder: '请选择具体选项',
    tags: false,
    multiple: false,
    width: 'element'
  })
  setTimeout(()=>{$('#tempmlScript').remove()}, 0)
</script>
  `.trim()
  /** 多选模板 */
  let multipleTempl = `
<div class="input_wrap multiple_select">
  <div class="title"><input type="text" form='not_submit' name="hidden_free[${freeCounter}][${lineCounter}][title]" id="hidden_free_${freeCounter}_${lineCounter}_title" placeholder="名称"></div>
  <!-- 固定隐藏input，用于后端分辨该行表单类型 -->
  <input type='hidden' name='type' value='3'>
  <div class="alt_data">
    <select
      form = 'not_submit' name="hidden_free[${freeCounter}][${lineCounter}][alt_data]" id="hidden_free_${freeCounter}_${lineCounter}_alt_data"
    >
      <option></option>
      <optgroup label="">
          <option value="同时符合">同时符合</option>
          <option value="任意符合">任意符合</option>
        </optgroup>
    </select>
  </div>
  <div class="main_data">
      <select
        form = 'not_submit' name="hidden_free[${freeCounter}][${lineCounter}][main_data][]" id="hidden_free_${freeCounter}_${lineCounter}_main_data"
      >
      <option inori-id='here-inori'></option>
      </select>
  </div>
  <div class="button" onclick='deleteThisHiddenLine(this)'>
    <button onclick='deleteThisHiddenLine(this)'>删除</button>
  </div>
</div>
<script id='tempmlScript'>
  $('#hidden_free_${freeCounter}_${lineCounter}_alt_data').select2({
    placeholder: '请选择具体选项（必填）',
    tags: false,
    multiple: false,
    width: 'element'
  }).val(null).trigger('change')
  $('#hidden_free_${freeCounter}_${lineCounter}_main_data').select2({
    placeholder: '请选择具体选项（必填）',
    // tags: true,
    multiple: true,
    tokenSeparators: [',', ' '],
    width: 'element',
    closeOnSelect: false
  }).val(null).trigger('change')
  setTimeout(()=>{$('#tempmlScript').remove()}, 0)
</script>
  `.trim()

  let type = $(_this).parent().siblings('.addNewHiddenFormLineType').val()
  if (type === '1') {
    // 数字输入
    $(`#hidden_free_${freeCounter}>div:last-child`).before(numberTempl)
  } else if (type === '2') {
    // 设定全局数据存放点
    let singleTemplName = 'singleTempl'
    if (window.inori_var === undefined) window.inori_var = {}
    window.inori_var[singleTemplName] = singleTempl
    // 弹层先填写选项
    openFreeSingleOption(singleTemplName)
    // 单选框
    // 异步的原因，下一步将会异步调用以下函数
    if (window.inori_func === undefined) window.inori_func = {}
    window.inori_func.addNewSinglLine = function (Arrayname, templName) {
      // Arrayname  为数组位置，目前是固定值，函数结束前undefined
      // templName  为模板位置，目前是固定值，函数结束前undefined
      const optionListArray = window[Arrayname]
      if (window.inori_var === undefined) window.inori_var = {}
      let templ = window.inori_var[templName]
      window[Arrayname] = undefined
      window.inori_var[templName] = undefined
      let optionList = '<optgroup label="">'
      // 去重数组
      let tempArray = []
      $.each(optionListArray, function (e, i) {
        if (tempArray.indexOf(i.value) === -1) {
          tempArray.push(i.value)
          optionList += `<option value='${i.value}' inori-data='${i.name}'>${i.value}</option>`
        }
      })
      optionList += '</optgroup>'
      templ = templ.replace(/<option inori-id='here-inori'><\/option>/, `<option></option>${optionList}`)
      $(`#hidden_free_${freeCounter}>div:last-child`).before(templ)
    }
  } else if (type === '3') {
    // 设定全局数据存放点
    let MultipleTemplName = 'MultipleTempl'
    if (window.inori_var === undefined) window.inori_var = {}
    window.inori_var[MultipleTemplName] = multipleTempl
    // 弹层先填写选项
    openFreeMultipleOption(MultipleTemplName)
    // 多选框
    // 异步的原因，下一步将会异步调用以下函数
    if (window.inori_func === undefined) window.inori_func = {}
    window.inori_func.addNewMultiplelLine = function (Arrayname, templName) {
      // Arrayname  为数组位置，目前是固定值，函数结束前undefined
      // templName  为模板位置，目前是固定值，函数结束前undefined
      const optionListArray = window[Arrayname]
      if (window.inori_var === undefined) window.inori_var = {}
      let templ = window.inori_var[templName]
      window[Arrayname] = undefined
      window.inori_var[templName] = undefined
      let optionList = '<optgroup label="">'
      // 去重数组
      let tempArray = []
      $.each(optionListArray, function (e, i) {
        if (tempArray.indexOf(i.value) === -1) {
          tempArray.push(i.value)
          optionList += `<option value='${i.value}' inori-data='${i.name}'>${i.value}</option>`
        }
      })
      optionList += '</optgroup>'
      templ = templ.replace(/<option inori-id='here-inori'><\/option>/, `${optionList}`)
      $(`#hidden_free_${freeCounter}>div:last-child`).before(templ)
    }
    // 复选框
    // $(`#hidden_free_${freeCounter}>div:last-child`).before(multipleTempl)
  } else {
    alert('请选择有效选项')
  }
  evt.preventDefault()
  // 执行完毕添加写入计数自增
  $(_this).closest('.addNewHiddenFormLine').siblings('.hiddenLineCounter').val(lineCounter)
}
/** 用于移除当前指定的DIY表单行，也就是一个问题 */
function deleteThisHiddenLine (_this) {
  $(_this).closest('.input_wrap').remove()
  window.event.preventDefault()
}

/** 提交当前DIY表单 */
function postThisHiddenLine (_this, event, isSecond) {
  event.preventDefault()

  /** 获取类型为Number的表单(结构) */
  function getWholeNumber (_this, index, uID) {
    let title = !($(_this).find(`[name$='\[title\]']`).val().replace(/\s/g, '') === '') ? $(_this).find(`[name$='\[title\]']`).val() : void ((() => { /* alert('请填写选项！') */;console.log($(_this).find(`[name$='\[title\]']`).val()) })())
    // 所有的alt_data都为固定值所以就不传具体参数了
    let altData = !($(_this).find(`[name$='\[alt_data\]']`).val() === '') ? $(_this).find(`[name$='\[alt_data\]']`).val() : void ((() => { /* alert('请填写选项！') */ })())
    let mainData = !($(_this).find(`[name$='\[main_data\]']`).val().replace(/\s/g, '') === '') ? $(_this).find(`[name$='\[main_data\]']`).val().replace(/\s/g, '') : void ((() => { /* alert('请填写选项！') */;console.log($(_this).find(`[name$='\[title\]']`).val()) })())
    return {
      input_type: 1,
      title: title,
      alt_data: altData,
      main_data: mainData,
      group: uID
    }
  }
  /** 获取类型为单选的表单(结构) */
  function getWholeSingleS (_this, index, uID) {
    let title = !($(_this).find(`[name$='\[title\]']`).val().replace(/\s/g, '') === '') ? $(_this).find(`[name$='\[title\]']`).val() : void ((() => { /* alert('请填写选项！') */ })())
    // altData
    // let altData = $(_this).find(`[name$='\[alt_data\]']`).val()
    let mainData = $(_this).find(`[name$='\[main_data\]']`).find('option').map(function () {
      if ($(this).attr('value')) {
        /** 自增数字 */
        let key = $(this).attr('inori-data')
        /** 用户输入的内容 */
        let value = $(this).attr('value')
        /** 用户输入的内容 */
        let text = $(this).text()
        let checked = $(_this).find(`[name$='\[main_data\]']`).val() === value
        return {
          key: key,
          value: value,
          text: text,
          checked: checked,
          index: `${uID}_${index}`
        }
      }
    })
    // jq 对象不能用来提交
    let temp = []
    mainData.each(function (index, ele) {
      temp.push(ele)
    })
    mainData = temp
    if (mainData.length === 0) {
      // alert('请填写单选选项')
      return
    }
    return {
      input_type: 2,
      title: title,
      alt_data: '',
      main_data: mainData,
      group: uID
    }
  }
  /** 获取类型为多选的表单(结构) */
  function getWholeMultipleS (_this, index, uID) {
    let title = !($(_this).find(`[name$='\[title\]']`).val().replace(/\s/g, '') === '') ? $(_this).find(`[name$='\[title\]']`).val() : void ((() => { /* alert('请填写选项！') */ })())
    // altData为固定值，不传详细
    let altData = !($(_this).find(`[name$='\[alt_data\]']`).val() === '') ? $(_this).find(`[name$='\[alt_data\]']`).val() : void ((() => { /* alert('请填写选项！') */ })())
    let mainData = $(_this).find(`[name$='\[main_data\]\[\]']`).find('option').map(function () {
      if ($(this).attr('value')) {
        /** 自增数字 */
        let key = $(this).attr('inori-data')
        /** 用户输入的内容 */
        let value = $(this).attr('value')
        /** 用户输入的内容 */
        let text = $(this).text()
        let checked = !($(_this).find(`[name$='\[main_data\]\[\]']`).val().indexOf(value) === -1)
        return {
          key: key,
          value: value,
          text: text,
          checked: checked,
          index: `${uID}_${index}`
        }
      }
    })
    if (mainData.length === 0) {
      // alert('请填写单选选项')
      return
    }
    let temp = []
    mainData.each(function (index, ele) {
      temp.push(ele)
    })
    mainData = temp
    return {
      input_type: 3,
      title: title,
      alt_data: altData,
      main_data: mainData,
      group: uID
    }
  }

  /** 获取类型为Number的表单数据 */
  function getWholeNumberOnly (_this, index, uID) {
    // 所有的alt_data都为固定值所以就不传具体参数了
    let altData = !($(_this).find(`[name$='\[alt_data\]']`).val() === '') ? $(_this).find(`[name$='\[alt_data\]']`).val() : void ((() => { /* alert('请填写选项！') */ })())
    let mainData = !($(_this).find(`[name$='\[main_data\]']`).val().replace(/\s/g, '') === '') ? $(_this).find(`[name$='\[main_data\]']`).val().replace(/\s/g, '') : void ((() => { /* alert('请填写选项！') */ })())
    return {
      input_type: 1,
      m_group: `${uID}_${index}`,
      mainData: mainData,
      altData: altData,
      bq_id: uID
    }
  }
  /** 获取类型为单选的表单数据 */
  function getWholeSingleSOnly (_this, index, uID) {
    let mainData = $(_this).find(`[name$='\[main_data\]']`).find('option').map(function () {
      if ($(_this).find(`[name$='\[main_data\]']`).val() === $(this).attr('value')) {
        /** 自增数字 */
        let key = $(this).attr('inori-data')
        return key
      }
    })
    if (mainData.length === 0) {
      // alert('请填写单选选项')
    } else {
      return {
        input_type: 2,
        m_group: `${uID}_${index}`,
        mainData: mainData[0],
        altData: '',
        bq_id: uID
      }
    }
  }
  /** 获取类型为多选的表单数据 */
  function getWholeMultipleSOnly (_this, index, uID) {
    let altData = !($(_this).find(`[name$='\[alt_data\]']`).val() === '') ? $(_this).find(`[name$='\[alt_data\]']`).val() : void ((() => { /* alert('请填写选项！') */ })())
    let mainData = $(_this).find(`[name$='\[main_data\]\[\]']`).find('option').map(function () {
      if (($(_this).find(`[name$='\[main_data\]\[\]']`).val().indexOf($(this).attr('value')) > -1)) {
        /** 自增数字 */
        let key = $(this).attr('inori-data')
        return key
      }
    })
    // 不能提交jq对象数组
    let temp = []
    mainData.each(function (index, ele) {
      temp.push(ele)
    })
    mainData = temp
    if (altData === '' || mainData.length === 0) {
      /* alert('请填写相关多选选项') */
    }
    else {
      return {
        input_type: 3,
        m_group: `${uID}_${index}`,
        mainData: temp.join(','),
        altData: altData,
        bq_id: uID
      }
    }
  }
  let urlBase = $('#hidden_free_url_base').val()
  // 小类包裹
  let wholeWrap = $(_this).closest(`div.hdden_free_wrap`)
  // // 单行选择包裹（列表）
  let lineWrap = wholeWrap.children(`.input_wrap`)
  let hId = wholeWrap.children(`input[name$='\[id\]']`).val()
  let hValue = wholeWrap.children(`input[name$='\[value\]']`).val()
  let hData = []
  let hDataOnly = []
  lineWrap.each(function (index) {
    let type = $(this).children(`[name='type']`).length === 1 ? $(this).children(`[name='type']`).val() : void (() => { alert('严重错误') })
    let switchObj = {
      1: getWholeNumber,
      2: getWholeSingleS,
      3: getWholeMultipleS
    }
    let switchDataObj = {
      1: getWholeNumberOnly,
      2: getWholeSingleSOnly,
      3: getWholeMultipleSOnly
    }
    hData.push(switchObj[type](this, index, hId))
    hDataOnly.push(switchDataObj[type](this, index, hId))
  })
  let ajaxDta = {
    m_group: hId,
    m_value: hValue,
    formData: hData
  }
  let ajaxDtaAlt = {
    m_goods: location.href.match(/\/id\/(\d+)/)[1],
    m_goods_dID: location.href.match(/\/did\/(\d+)/)[1],
    m_group: hId,
    m_value: hValue,
    formData: hDataOnly
  }
  console.clear()
  console.log('提交的数据:')
  console.log('1、结构:')
  console.dir(ajaxDta)
  console.log('2、数据:')
  console.dir(ajaxDtaAlt)
  console.log('服务器返回的数据:')
  let shouldAbortSubmit = false
  $.each(ajaxDtaAlt.formData, (index, item) => {
    if (`${item}` === 'undefined' || `${item.mainData}` === 'undefined') {
      shouldAbortSubmit = true
    }
  })
  if (shouldAbortSubmit) {
    alert('请完整填写DIY表单')
    return
  }
  let DIYPOSTajax = {}
  if (isSecond !== undefined && isSecond === 'second') {
    const urlBaseAlt = String($('#hidden_free_data_url_base').val())
    postFIYData(urlBaseAlt)
  } else {
    DIYPOSTajax = $.ajax(String(urlBase), {
      method: 'POST',
      data: ajaxDta,
      success: function (data) {
        if (data.code === 1) {
          const urlBaseAlt = String($('#hidden_free_data_url_base').val())
          postFIYData(urlBaseAlt)
        } else {
          console.dir(data)
        }
      },
      error: function () {
        alert('网络发生错误，请重试')
      }
    })
  }

  DIYPOSTajax._this = _this
  DIYPOSTajax._uid = hId
  function postFIYData (urlBaseAlt) {
    $.ajax(urlBaseAlt, {
      method: 'POST',
      data: ajaxDtaAlt,
      success: function (data) {
        if (data.code === 1) {
          console.log('提交成功')
          removeAltButton(DIYPOSTajax._this)
          let _value = data.data.join(',')
          let id = `<input type='hidden' name = 'check_xiaolei[]' inori-diy-data='${DIYPOSTajax._uid}' value='${_value}'>`
          $('#all').append(id)
        }
      },
      error: function () {
        console.log('提交失败')
      }
    })
  }
}

/** 锁定相应DIY表单，隐藏修改相关的按钮 */
function removeAltButton (_this) {
  $(_this).closest('.hdden_free_wrap').find('.addNewHiddenFormLine').remove()
  $(_this).closest('.hdden_free_wrap').find('.button').remove()
}
